<?php
/**
 * User
 * Created by Veyron
 * motto:现在的拼搏 为了更好的明天
 * day:  2020/1/21
 * Time: 17:14
 */

namespace app\common\business;
use app\common\lib\Str;
use app\common\lib\Time;
use app\common\model\mysql\User as UserModel;
use think\Exception;

class User
{
    public $userObj = null;
    public function __construct()
    {
        $this->userObj = new UserModel();
    }
    public function login($data){
        $redisCode = cache(config('redis.code_pre').$data['phone_number']);
        if(empty($redisCode) || $redisCode != $data['code']){
            throw new Exception('不存在该验证码',config('status.code_null'));
        }
        //判断是否有 用户记录
        //生成 token
        $user = $this->userObj->getUserByPhoneNumber($data['phone_number']);

        if(!$user){
            //用户不存在，新增用户
            $username = 'vy-'. $data['phone_number'];
            $userData = [
                'username' => $username,
                'phone_number' => $data['phone_number'],
                'type'  =>  $data['type'],
                'status' => config('status.mysql.table_normal')
            ];
            try{
                $this->userObj->save($userData);
                $userId = $this->userObj->id;
            }catch (Exception $e){
                throw new Exception('数据库内部异常');
            }
        }else{
            // 更新记录
            $updateData = [
                'last_login_ip'   =>  request()->ip(),
                'last_login_time' => time(),
            ];
            $userId = $user['id'];
            $username = $user['username'];
            $this->userObj->updateById($userId,$updateData);
        }
        $token = Str::getLoginToken($data['phone_number']);
        $redisData = [
            'id' => $userId,
            'username' => $username
        ];
        $res = cache(config('redis.token_pre').$token,$redisData, Time::getLoginExpiresTime($data['type']));

        return $res ? ['token'=>$token,'username'=>$username] : false;
    }

    /**
     * 根据id获取正常用户信息
     * @param $userId
     */
    public function getNormalUserById($userId){
        $user = $this->userObj->getUserById($userId);
        if(!$user || $user->status != config('status.mysql.table_normal')){
            return [];
        }
        return $user->toArray();
    }
    /**
     * 根据用户名获取正常用户信息
     * @param $userId
     */
    public function getNormalUserByUsername($username){
        $user = $this->userObj->getUserByUsername($username);
        if(!$user || $user->status != config('status.mysql.table_normal')){
            return [];
        }
        return $user->toArray();
    }
    /**
     * 更新用户信息
     * @param $userId
     * @param $data
     */
    public function update($userId,$data){
        $user = $this->getNormalUserById($userId);
        if(!$user){
            throw new Exception('该用户不存在');
        }
        //检查用户名是否存在
        $userResult = $this->getNormalUserByUsername($data['username']);
        if($userResult && $userResult['id'] != $userId){
            throw new Exception('用户名已存在请重新设置');
        }

        return $this->userObj->updateById($userId,$data);
    }
}
